using System.Configuration;
using System.Web;
using System.Xml;
using Wikey.Utilities.Extensions;

namespace Wikey.Domain.Components
{
    public class Configuration {
        private static readonly Configuration _configuration = 
            (Configuration)ConfigurationManager.GetSection("Wikey/Web");
        private readonly string ConnectionString;

        public static Configuration GetConfig() {
            return _configuration;
        }
        public string Connection {
            get { return ConnectionString; }
        }

        public Configuration(XmlNode node) {
            if (node == null) {
                throw new ConfigurationErrorsException("Missing configuration CodeBetter.Canvas/Web");
            }
            ConnectionString = node.GetString("connectionString");
            ConnectionString = MakeRelative(ConnectionString);
        }
        private static string MakeRelative(string value) {
            if (!string.IsNullOrEmpty(value) && value.StartsWith("~") && 
                    HttpContext.Current != null) {
                return HttpContext.Current.Server.MapPath(value);
            }
            return value;
        }
    }

    public class ConfigurationHandler : IConfigurationSectionHandler {
        public object Create(object parent, object configContext, XmlNode section) {
            return new Configuration(section);
        }
    }
}